//
//  Date-Extensation.swift
//  weibo
//
//  Created by 叶子韬韬 on 2017/5/3.
//  Copyright © 2017年 叶子韬韬. All rights reserved.
//

import Foundation

extension Date {
    
    static func createDateString(createdTime:String) -> String{
        
        //创建时间格式化对象
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = Locale(identifier: "en")
        
        guard let createDate = fmt.date(from: createdTime) else {
            return ""
        }
        
        //创建当前时间
        let nowDate = NSDate()
        
        //计算当前时间和创建的时间差
        let interval = Int(nowDate.timeIntervalSince(createDate))
        
        //对时间间隔处理
        if interval < 60 {
            
            return "刚刚"
        }
        if interval < 60*60 {
           
            return "\(interval/60)分钟前"
        }
        
        if interval < 60*60*24 {
          
            return "\(interval/(60*24))小时前"
        }
        
        
        //创建日历对象
        let calender = NSCalendar.current
        
        //处理昨天时间：
        if calender.isDateInYesterday(createDate) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr = fmt.string(from: createDate)
           
            return timeStr
        }
        
        
        //处理一年之内的时间
        let cmps = (calender as NSCalendar).components(.year, from: createDate, to: nowDate as Date, options: [])
        
        if cmps.year! < 1 {
            fmt.dateFormat = "MM-dd HH:mm"
            let timerStr = fmt.string(from: createDate)
           
            return timerStr
            
        }
        
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        let timerStr = fmt.string(from: createDate)
       
        
        return timerStr


    }
}
